package com.jcsz.gulimall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.jcsz.gulimall.product.service.CategoryBrandRelationService;
import com.jcsz.gulimall.product.vo.Catelog2Vo;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jcsz.common.utils.PageUtils;
import com.jcsz.common.utils.Query;

import com.jcsz.gulimall.product.dao.CategoryDao;
import com.jcsz.gulimall.product.entity.CategoryEntity;
import com.jcsz.gulimall.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;

    @Autowired
    private RedissonClient redissonClient;


    @Override
    public List<CategoryEntity> queryPageTree() {
        List<CategoryEntity> categoryEntities = baseMapper.selectList(null);
        List<CategoryEntity> categors = categoryEntities.stream()
                .filter(categoryEntity -> categoryEntity.getParentCid() == 0)
                .map(categoryEntity -> {
                    categoryEntity.setChildrenCategoryEntities(getchildrenCategorys(categoryEntity, categoryEntities));
                    return categoryEntity;
                })
                .sorted(Comparator.comparingInt(o -> (o.getSort() == null ? 0 : o.getSort())))
                .collect(Collectors.toList());
        return categors;
    }


    List<CategoryEntity> getchildrenCategorys(CategoryEntity root, List<CategoryEntity> categoryEntities) {
        List<CategoryEntity> collects = categoryEntities.stream()
                .filter(categoryEntity -> categoryEntity.getParentCid() == root.getCatId())
                .map(categoryEntity -> {
                    categoryEntity.setChildrenCategoryEntities(getchildrenCategorys(categoryEntity, categoryEntities));
                    return categoryEntity;
                })
                .sorted(Comparator.comparingInt(o -> (o.getSort() == null ? 0 : o.getSort())))
                .collect(Collectors.toList());
        return collects;
    }

    @Override
    public void removeMenuByIds(List<Long> asList) {
        baseMapper.deleteBatchIds(asList);
    }

    @Override
    public Long[] getCatelogPathById(Long catelogId) {
        List<Long> ids = new ArrayList<>();
        Collections.reverse(getCatelogPath(catelogId, ids));
        return ids.toArray(new Long[ids.size()]);
    }

    private List<Long> getCatelogPath(Long catelogId, List<Long> ids) {

        CategoryEntity category = getById(catelogId);
        if (category != null) {
            ids.add(catelogId);
            if (category.getParentCid() != 0) {
                getCatelogPath(category.getParentCid(), ids);
            }
            return ids;
        }

        return null;

    }

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }


    //    @Caching(evict={
//            @CacheEvict(value = {"category"}, key = "'getLevel1Catagories'"),
//            @CacheEvict(value = {"category"}, key = "'getCatlogJson'")
//    })
    @CacheEvict(value = {"category"}, allEntries = true)
    @Override
    public void updateCategory(CategoryEntity category) {
        this.updateById(category);
        if (!StringUtils.isEmpty(category.getName())) {
            categoryBrandRelationService.updateCategoryName(category.getCatId(), category.getName());
        }
    }

    // 调用该方法时会将结果缓存，缓存名为category，key为方法名
// sync表示该方法的缓存被读取时会加锁 // value等同于cacheNames // key如果是字符串"''"
    @Cacheable(value = {"category"}, key = "#root.methodName")//存放缓存
    @Transactional
    @Override
    public List<CategoryEntity> getLevel1Catagories() {
        System.out.println("查询数据库.....getLevel1Catagories");
        List<CategoryEntity> list = this.list(new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));
        return list;
    }

    @Cacheable(value = {"category"}, key = "'getCatlogJson'")
    @Override
    public Map<String, List<Catelog2Vo>> getCatlogJson() {

        System.out.println("getCatlogJsonFromDB缓存未命中,查询数据库.....");
        List<CategoryEntity> allCategorys = list();
        //Map<String, List<Catelog2Vo>> map = new HashMap<>();
        List<CategoryEntity> level1Catagories = getCategoryByParentCid(allCategorys, 0L);

        Map<String, List<Catelog2Vo>> collect = level1Catagories.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            List<CategoryEntity> level2Catagories = getCategoryByParentCid(allCategorys, v.getCatId());
            List<Catelog2Vo> catelog2Vos = null;
            if (level2Catagories != null && level2Catagories.size() > 0) {
                catelog2Vos = level2Catagories.stream().map(v2 -> {
                    Catelog2Vo catelog2Vo = new Catelog2Vo();
                    catelog2Vo.setCatalog1Id(v.getCatId().toString());
                    catelog2Vo.setId(v2.getCatId().toString());
                    catelog2Vo.setName(v2.getName());
                    List<CategoryEntity> level3Catagories = getCategoryByParentCid(allCategorys, v2.getCatId());
                    List<Catelog2Vo.Catelog3Vo> catelog3Vos = null;
                    if (level3Catagories != null && level3Catagories.size() > 0) {
                        catelog3Vos = level3Catagories.stream().map(v3 -> {
                            Catelog2Vo.Catelog3Vo catelog3Vo = new Catelog2Vo.Catelog3Vo();
                            catelog3Vo.setCatalog2Id(v2.getCatId().toString());
                            catelog3Vo.setName(v3.getName());
                            catelog3Vo.setId(v3.getCatId().toString());
                            return catelog3Vo;
                        }).collect(Collectors.toList());

                    }
                    catelog2Vo.setCatalog3List(catelog3Vos);

                    return catelog2Vo;
                }).collect(Collectors.toList());

            }
            return catelog2Vos;
        }));
        return collect;
    }

    public Map<String, List<Catelog2Vo>> getCatlogJson2() {
        String catlog_json = redisTemplate.opsForValue().get("catlog_json");
        if (StringUtils.isEmpty(catlog_json)) {
            Map<String, List<Catelog2Vo>> catlogJsonFromDB = getCatalogJsonFromDbWithRedissonLock();
            return catlogJsonFromDB;
        }
        System.out.println("缓存命中.....");
        Map<String, List<Catelog2Vo>> result = JSON.parseObject(catlog_json, new TypeReference<Map<String, List<Catelog2Vo>>>() {
        });
        return result;
    }

    public Map<String, List<Catelog2Vo>> getCatalogJsonFromDbWithRedissonLock() {

        Map<String, List<Catelog2Vo>> catlogJsonFromDB;
        RLock lock = redissonClient.getLock("catlog_json_lock");
        try {
            lock.lock();
            System.out.println("获取分布式锁成功.....");
            catlogJsonFromDB = getCatlogJsonFromDB();
        } finally {
            lock.unlock();
        }
        return catlogJsonFromDB;


    }

    public Map<String, List<Catelog2Vo>> getCatalogJsonFromDbWithRedisLock() {
        //1、占分布式锁。去redis占坑      设置过期时间必须和加锁是同步的，保证原子性（避免死锁）
        String uuid = UUID.randomUUID().toString();
        Boolean result = redisTemplate.opsForValue().setIfAbsent("lock", uuid, 300, TimeUnit.SECONDS);

        if (result) {
            Map<String, List<Catelog2Vo>> catlogJsonFromDB = null;
            System.out.println("获取分布式锁成功.....");
            try {
                catlogJsonFromDB = getCatlogJsonFromDB();
            } finally {
                String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
                //删除锁
                redisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class), Arrays.asList("lock"), uuid);
            }
            return catlogJsonFromDB;
        } else {
            System.out.println("获取分布式锁失败...等待重试...");
            try {
                Thread.sleep(500);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return getCatalogJsonFromDbWithRedisLock();
        }


    }

    public Map<String, List<Catelog2Vo>> getCatlogJsonWithLocalLock() {

        synchronized (this) {
            //从数据库查询前再次查看缓存
            String catlog_json = redisTemplate.opsForValue().get("catlog_json");
            if (!StringUtils.isEmpty(catlog_json)) {
                Map<String, List<Catelog2Vo>> result = JSON.parseObject(catlog_json, new TypeReference<Map<String, List<Catelog2Vo>>>() {
                });
                return result;
            }
            System.out.println("缓存未命中,查询数据库.....");
            List<CategoryEntity> allCategorys = list();
            //Map<String, List<Catelog2Vo>> map = new HashMap<>();
            List<CategoryEntity> level1Catagories = getCategoryByParentCid(allCategorys, 0L);

            Map<String, List<Catelog2Vo>> collect = level1Catagories.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
                List<CategoryEntity> level2Catagories = getCategoryByParentCid(allCategorys, v.getCatId());
                List<Catelog2Vo> catelog2Vos = null;
                if (level2Catagories != null && level2Catagories.size() > 0) {
                    catelog2Vos = level2Catagories.stream().map(v2 -> {
                        Catelog2Vo catelog2Vo = new Catelog2Vo();
                        catelog2Vo.setCatalog1Id(v.getCatId().toString());
                        catelog2Vo.setId(v2.getCatId().toString());
                        catelog2Vo.setName(v2.getName());
                        List<CategoryEntity> level3Catagories = getCategoryByParentCid(allCategorys, v2.getCatId());
                        List<Catelog2Vo.Catelog3Vo> catelog3Vos = null;
                        if (level3Catagories != null && level3Catagories.size() > 0) {
                            catelog3Vos = level3Catagories.stream().map(v3 -> {
                                Catelog2Vo.Catelog3Vo catelog3Vo = new Catelog2Vo.Catelog3Vo();
                                catelog3Vo.setCatalog2Id(v2.getCatId().toString());
                                catelog3Vo.setName(v3.getName());
                                catelog3Vo.setId(v3.getCatId().toString());
                                return catelog3Vo;
                            }).collect(Collectors.toList());

                        }
                        catelog2Vo.setCatalog3List(catelog3Vos);

                        return catelog2Vo;
                    }).collect(Collectors.toList());

                }
                return catelog2Vos;
            }));
            String jsonString = JSON.toJSONString(collect);
            //设置过期时间解决缓存雪崩
            redisTemplate.opsForValue().set("catlog_json", jsonString, 1, TimeUnit.DAYS);
            return collect;

        }

    }

    public Map<String, List<Catelog2Vo>> getCatlogJsonFromDB() {

        //从数据库查询前再次查看缓存
        String catlog_json = redisTemplate.opsForValue().get("catlog_json");
        if (!StringUtils.isEmpty(catlog_json)) {
            Map<String, List<Catelog2Vo>> result = JSON.parseObject(catlog_json, new TypeReference<Map<String, List<Catelog2Vo>>>() {
            });
            return result;
        }
        System.out.println("getCatlogJsonFromDB缓存未命中,查询数据库.....");
        List<CategoryEntity> allCategorys = list();
        //Map<String, List<Catelog2Vo>> map = new HashMap<>();
        List<CategoryEntity> level1Catagories = getCategoryByParentCid(allCategorys, 0L);

        Map<String, List<Catelog2Vo>> collect = level1Catagories.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            List<CategoryEntity> level2Catagories = getCategoryByParentCid(allCategorys, v.getCatId());
            List<Catelog2Vo> catelog2Vos = null;
            if (level2Catagories != null && level2Catagories.size() > 0) {
                catelog2Vos = level2Catagories.stream().map(v2 -> {
                    Catelog2Vo catelog2Vo = new Catelog2Vo();
                    catelog2Vo.setCatalog1Id(v.getCatId().toString());
                    catelog2Vo.setId(v2.getCatId().toString());
                    catelog2Vo.setName(v2.getName());
                    List<CategoryEntity> level3Catagories = getCategoryByParentCid(allCategorys, v2.getCatId());
                    List<Catelog2Vo.Catelog3Vo> catelog3Vos = null;
                    if (level3Catagories != null && level3Catagories.size() > 0) {
                        catelog3Vos = level3Catagories.stream().map(v3 -> {
                            Catelog2Vo.Catelog3Vo catelog3Vo = new Catelog2Vo.Catelog3Vo();
                            catelog3Vo.setCatalog2Id(v2.getCatId().toString());
                            catelog3Vo.setName(v3.getName());
                            catelog3Vo.setId(v3.getCatId().toString());
                            return catelog3Vo;
                        }).collect(Collectors.toList());

                    }
                    catelog2Vo.setCatalog3List(catelog3Vos);

                    return catelog2Vo;
                }).collect(Collectors.toList());

            }
            return catelog2Vos;
        }));
        String jsonString = JSON.toJSONString(collect);
        redisTemplate.opsForValue().set("catlog_json", jsonString, 1, TimeUnit.DAYS);
        return collect;

    }

    private List<CategoryEntity> getCategoryByParentCid(List<CategoryEntity> allCategorys, Long parentCid) {

        return allCategorys.stream().filter(item -> item.getParentCid() == parentCid).collect(Collectors.toList());
    }
}